<script>
import { deepClone } from '../../utils/index'
import render from '../render/render.js'

const ruleTrigger = {
  'el-input': 'blur',
  'el-input-number': 'blur',
  'el-select': 'change',
  'el-radio-group': 'change',
  'el-checkbox-group': 'change',
  'el-cascader': 'change',
  'el-time-picker': 'change',
  'el-date-picker': 'change',
  'el-rate': 'change'
}

const layouts = {
  colFormItem(h, scheme) {
    const config = scheme.__config__
    const listeners = buildListeners.call(this, scheme)

    let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null
    if (config.showLabel === false) labelWidth = '0'
    return (
      // <el-col span={config.span}>
      //   <el-form-item label-width={labelWidth} prop={scheme.__vModel__}
        <el-form-item  prop={scheme.__vModel__}
          label={config.showLabel ? config.label : ''}>
          <render conf={scheme} on={listeners} />
        </el-form-item>
      // </el-col>
    )
  },
  rowFormItem(h, scheme) {
    let child = renderChildren.apply(this, arguments)
    if (scheme.type === 'flex') {
      child = {child}
    }
    return (
          {child}
    )
  }
}

function renderCustomFrom(h) {
    let applyFormData = [];
    let rules = [];
    return (
      <el-form style="width: 70%;margin-left:15%"
               props={{ model: applyFormData}}
               rules={rules}
               label-width="150px"
               ref="applyForm">
</el-form>
    )
}

function renderFrom(dataList, h) {
  const { formConfCopy } = this

  if(dataList[0].disabled == true){
    return (
      <el-form style="width: 70%;margin-left:15%"
        size={formConfCopy.size}
        label-position={formConfCopy.labelPosition}
        disabled={formConfCopy.disabled}
        // label-width={`${formConfCopy.labelWidth}px`}
        label-width="150px"
        ref={formConfCopy.formRef}
        // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
        props={{ model: this[formConfCopy.formModel] }}
        rules={this[formConfCopy.formRules]}
      >
        {renderFormItem.call(this, h, dataList)}
      </el-form>
    )
  }else{
    return (
      <el-form style="width: 70%;margin-left:15%"
        size={formConfCopy.size}
        label-position={formConfCopy.labelPosition}
        disabled={formConfCopy.disabled}
        // label-width={`${formConfCopy.labelWidth}px`}
        label-width="150px"
        ref={formConfCopy.formRef}
        // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
        props={{ model: this[formConfCopy.formModel] }}
        rules={this[formConfCopy.formRules]}
      >
        {renderFormItem.call(this, h, dataList)}
        <div style="width: 30%;margin-left:35%;display:flex;justify-content: space-between;">
          <el-button  type="primary" onClick={this.submitForm}>提交</el-button>
          <el-button  onClick={this.resetForm}>重置</el-button>
        </div>
      </el-form>
    )
  }

}

function renderFroms(h) {
  const { formConfCopy } = this
  let allFormList = [];
  let fieldList = formConfCopy.fields;
  let allDataList = [];
  let currentList = [];
  if(fieldList){
    let stepIndex = -1;
    for (let i = 0; i < fieldList.length; i++) {
      let item = fieldList[i];
      if(item.stepIndex > stepIndex){
        if(currentList.length > 0){
          allDataList.push(currentList);
        }
        currentList = new Array();
        stepIndex = item.stepIndex;
      }

      if(item.__config__ && item.__config__.children){
        for (let j = 0; j < item.__config__.children.length; j++) {
          currentList.push(item.__config__.children[j]);
        }
      }else{
        currentList.push(item);
      }
    }
    if(currentList.length > 0){
      allDataList.push(currentList);
    }

    for (let i = 0; i < allDataList.length; i++) {
      let dataList = allDataList[i];
      let mForm = renderFrom.call(this, dataList, h);
      allFormList.push(mForm);
      let lastItem = dataList[dataList.length - 1];
      if(lastItem.disabled == true){
        let divider = <el-divider></el-divider>;
        allFormList.push(divider);
      }
    }

    let whole = <div style="width:100%">{allFormList}</div>

    return whole;

  }
}

function formBtns(h) {
  return
    <el-col>
    <el-form-item size="large">
      <el-button type="primary" size="mini" onClick={this.submitForm}>提交</el-button>
      <el-button onClick={this.resetForm}>重置</el-button>
    </el-form-item>
  </el-col>
}

function renderFormItem(h, elementList) {
  if (elementList) {
    let formItemList = [];
    for (let i = 0; i < elementList.length; i++) {
      let scheme = elementList[i];
      let config = scheme.__config__;
      let layout = layouts[config.layout];
      if (layout) {
        let formItem = layout.call(this, h, scheme);
        formItemList.push(formItem);
      }
    }
    return formItemList;
  }
}

function renderChildren(h, scheme) {
  const config = scheme.__config__
  if (!Array.isArray(config.children)) return null
  return renderFormItem.call(this, h, config.children)
}

function setValue(event, config, scheme) {
  this.$set(config, 'defaultValue', event)
  this.$set(this[this.formConf.formModel], scheme.__vModel__, event)
}

function buildListeners(scheme) {
  const config = scheme.__config__
  const methods = this.formConf.__methods__ || {}
  const listeners = {}

  // 给__methods__中的方法绑定this和event
  Object.keys(methods).forEach(key => {
    listeners[key] = event => methods[key].call(this, event)
  })
  // 响应 render.js 中的 vModel $emit('input', val)
  listeners.input = event => setValue.call(this, event, config, scheme)

  return listeners
}

export default {
  components: {
    render
  },
  props: {
    formConf: {
      type: Object,
      required: true
    }
  },
  data() {
    const data = {
      formConfCopy: deepClone(this.formConf),
      [this.formConf.formModel]: {},
      [this.formConf.formRules]: {}
    }
    if (data.formConfCopy.fields) {
      this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel])
      this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules])
    }
    return data
  },
  methods: {
    initFormData(componentList, formData) {
      componentList.forEach(cur => {
        const config = cur.__config__
        if (cur.__vModel__) formData[cur.__vModel__] = config.defaultValue
        if (config.children) this.initFormData(config.children, formData)
      })
    },
    buildRules(componentList, rules) {
      componentList.forEach(cur => {
        const config = cur.__config__
        if (Array.isArray(config.regList)) {
          if (config.required) {
            const required = { required: config.required, message: cur.placeholder }
            if (Array.isArray(config.defaultValue)) {
              required.type = 'array'
              required.message = `请至少选择一个${config.label}`
            }
            required.message === undefined && (required.message = `${config.label}不能为空`)
            config.regList.push(required)
          }
          rules[cur.__vModel__] = config.regList.map(item => {
            item.pattern && (item.pattern = eval(item.pattern))
            item.trigger = ruleTrigger && ruleTrigger[config.tag]
            return item
          })
        }
        if (config.children) this.buildRules(config.children, rules)
      })
    },
    resetForm() {
      this.formConfCopy = deepClone(this.formConf)
      this.$refs[this.formConf.formRef].resetFields()
    },
    submitForm() {
      this.$refs[this.formConf.formRef].validate(valid => {
        if (!valid) return false
        // 触发sumit事件
        // this.$emit('submit', this[this.formConf.formModel])
        const params = {
          formData: this.formConfCopy,
          valData: this[this.formConf.formModel]
        }
        this.$emit('submit', params)
        return true
      })
    },
    // 传值给父组件
    getData(){
      this.$emit('getData', this[this.formConf.formModel])
      // this.$emit('getData',this.formConfCopy)
    }
  },
  render(h) {
    // return renderFroms.call(this, h)
    return renderCustomFrom(h)
  }
}
</script>
